package com.wanmait.myhouse.filter;

import com.wanmait.myhouse.dao.ManagerDAO;
import com.wanmait.myhouse.vo.Manager;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter("/manager/*")
public class ManagerFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        String uri = httpServletRequest.getRequestURI();
        if (uri.contains("/login")||uri.contains(".jpg")||uri.contains(".gif")||uri.contains(".png")||uri.contains(".css")||uri.contains("verifyLogin")){
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        HttpSession session = httpServletRequest.getSession();
        Object o = session.getAttribute("manager");
        if (o == null){
            Cookie[] cookies = httpServletRequest.getCookies();
            if (cookies != null){
                Manager manager = new Manager();
                for (Cookie cookie : cookies){
                    if (cookie.getName().equals("managerName")){
                        manager.setManagerName(cookie.getValue());
                    }
                    if (cookie.getName().equals("managerPass")){
                        manager.setManagerPass(cookie.getValue());
                    }
                }
                ManagerDAO managerDAO = new ManagerDAO();
                Manager login = managerDAO.verLogin(manager);
                if (login != null){
                    session.setAttribute("manager",login);
                    filterChain.doFilter(servletRequest, servletResponse);
                }else {
                    HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
                    httpServletResponse.sendRedirect("/myhouse/manager/login");
                }
            }else {
                HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
                httpServletResponse.sendRedirect("/myhouse/manager/login");
            }
        }
        else {
            filterChain.doFilter(servletRequest, servletResponse);
        }
    }
}
